<?php

namespace App\Admin\Controllers\Patent;

use App\Admin\Actions\BatchAction\BatchPatentApplyReview;
use App\Admin\Actions\Review\PatentReviewPost;
use App\Admin\Actions\Tools\AssignAgencyBatchAction;
use App\Admin\Actions\Tools\PatentApplyFundingBatchAction;
use App\Admin\Controllers\Actions\Post\PatentAssessPost;
use App\Agency;
use App\Extensions\Actions\Post\GrantPatentPost;
use App\Extensions\Actions\Upload\PatentApplyFileUploadAction;
use App\Extensions\Content;
use App\Extensions\Exporters\PatentApplyExporter;
use App\Http\Controllers\Controller;
use App\Models\Department;
use App\PatentApply;
use App\Repositories\PatentApplyRepository;
use App\Services\Patent\PatentApplyColumnService;
use App\Services\Patent\PatentApplyService;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Encore\Admin\Widgets\Tab;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;

class PatentApplyController extends Controller
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected string $title = '专利申请前评估';
    protected PatentApplyService $service;
    public PatentApplyRepository $repository;
    protected PatentApplyColumnService $columnService;

    public function __construct(PatentApplyService $service, PatentApplyColumnService $columnService, PatentApplyRepository $repository)
    {
        $this->service = $service;
        $this->repository = $repository;
        $this->columnService = $columnService;
    }

    protected function title($type)
    {
        return data_get([
            '专利申请前评估',
            '专利申请中',
            '专利申请前评估未通过',
            '专利申请前评估退回修改'
        ], $type, '专利申请中');
    }

    public function index(Content $content, Request $request): Content
    {
        $action = $request->get('action');
        $type = data_get([0, 1, 2, 3], $action, 1);
        $grid = $this->grid(1, $type);
        $grid->model()->where('dept_review_status', 1)
            ->when($type == 1, function ($query) {
                $query->where('status', 0);
            })
            ->where('review_status', $type);
        $grid->tools(function (Grid\Tools $tools) use ($type) {
            $tools->append(new PatentApplyFundingBatchAction());
            if (!$type) {
                $tools->append(new AssignAgencyBatchAction());
                $tools->batch(function (Grid\Tools\BatchActions $batchActions) {
                    $batchActions->add(new BatchPatentApplyReview());
                });
            }
        });
        return $content
            ->title($this->title($type))
            ->body($grid);
    }

    protected function grid($role, $status)
    {
        $user = Admin::user();
        $grid = $this->repository->adminGrid();
        if ($status == 2) {
            $grid->disableActions();
        }
        if ($status || $role) {
            $grid->disableCreateButton();
        }
        $this->columnService->uuid($grid);
        $this->columnService->patent_name($grid);
        $this->columnService->patent_type($grid);
        $this->columnService->charge_person($grid);
        $this->columnService->department_name($grid);
        $this->columnService->agency($grid);
        $this->columnService->retrieval_report($grid);
        $this->columnService->score($grid, $role);
        $this->columnService->score_template($grid, $role);
        $this->columnService->pg_table($grid);
        //交底书
        $this->columnService->file($grid);
        if ($status == 1) {
            $this->columnService->cert($grid);
        }
        $this->columnService->review_status($grid);
        $grid->exporter((new PatentApplyExporter())->setRoleType($role));
        $grid->quickSearch(function ($query, $value) {
            $query->where(function (Builder $query) use ($value) {
                $query->where('patent_name', 'like', "%$value%")
                    ->orWhere('patent_sn', 'like', "%$value%")
                    ->orWhere('uuid', 'like', "%$value%")
                    ->orWhere('inventor', 'like', "%$value%")
                    ->orWhereHas('department', function ($query) use ($value) {
                        $query->where('name', 'like', "%$value%");
                    })->orWhereHas('agency', function ($query) use ($value) {
                        $query->where('name', 'like', "%$value%");
                    })->orWhereHas('experts', function ($query) use ($value) {
                        $query->where('name', 'like', "%$value%");
                    });
            });
        })->placeholder('关键字');
        $grid->filter(function (Grid\Filter $filter) {
            $filter->disableIdFilter();
            $filter->column(1 / 2, function (Grid\Filter $filter) {
                $filter->equal('department_id', __('dept_name'))->select(Department::all()->pluck('name', 'id'));
                $filter->equal('year', '申请年份')->year();
            });
            $filter->column(1 / 2, function (Grid\Filter $filter) {

                $filter->in('patent_type_id', '专利类型')->checkbox(patent_type_select_option());
                $filter->equal('agency_id', '代理机构')->select(Agency::selectAllOptions());
            });
        });
        $grid->actions(function (Grid\Displayers\Actions $actions) use ($user) {
            $actions->disableView();
            $actions->disableDelete();
            $actions->disableEdit();
            $row = $actions->row;
            if (!$row->review_status) {
                $actions->prepend(new PatentAssessPost($actions));
                $actions->prepend(new PatentReviewPost($actions));
            } elseif ($row->review_status == 1 && !$row->status) {
                $actions->prepend(new GrantPatentPost($actions));
            }
            if (!$row->review_status && $user->id == 1) {
                $actions->prepend(new PatentApplyFileUploadAction($actions));
            }
        });
        return $grid;
    }

    public function show($id, Content $content)
    {
        $model = PatentApply::query()->findOrFail($id);
        $tab = new Tab();
        $tab->add('基本信息', Admin::show($model, function (Show $show) use ($model) {
            $show->panel()->view('show.tab-panel');
            $show->field('uuid', __('登记编号'));
            $show->field('patent_name', __('Patent name'));
            $show->field('inventor', __('Inventor'));
            $show->field('charge_person', __('专利负责人'));
            $show->field('department.name', __('所属科室'));
            $show->field('contact_person', __('联系人'));
            $show->field('phone', __('联系电话'));
            $show->field('patent_person', __('patent_person'));
            $show->field('other_applicant', __('合作申请单位'));
            $show->field('patent_type_id', __('专利类型'))->using(patent_type_select_option());
            if ($model['patent_type_id'] == 4) {
                $show->field('other_patent_sn', __('国内申请号'));
            } elseif ($model['patent_type_id'] == 5) {
                $show->field('country', __('国家'));
                $show->field('apply_channel', __('途径'));
                $show->field('other_patent_sn', __('申请号'));
            }
            $show->field('file', __('交底书'))->as(function ($val) {
                return $val ? '下载' : '';
            })->link(file_custom_preview_url($model['file'], '(交底书)' . $model['patent_name']));
            $show->field('cert', __('专利证书'))->as(function ($val) {
                return $val ? '下载' : '';
            })->link(file_custom_preview_url($model['cert'], '(证书)' . $model['patent_name']));
            $show->field('review_remark', __('审核意见'));
        }));
        return $content
            ->isPage()
            ->body($tab);
    }

    public function download($id)
    {
        $model = $this->repository->find($id);
        if (!$model) {
            return response()->view('errors.404');
        }
        return $this->service->downloadTable($model);
    }


    protected function form()
    {
        return $this->repository->form();
    }

    public function destroy($id)
    {
        return $this->form()->destroy($id);
    }

}
